package com.shadow.baiqun.delegate.room.tilting;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.shadow.baiqun.R;
import com.shadow.baiqun.R2;
import com.shadow.baiqun.delegate.common.ResultConverter;
import com.shadow.baiqun.delegate.receive.SupplierEntry;
import com.shadow.baiqun.event.RefreshAddTurnEvent;
import com.shadow.core.delegate.RxShadowDelegate;
import com.shadow.core.net.callback.IError;
import com.shadow.core.net.callback.ISuccess;
import com.shadow.core.net.rx.RxRestClient;
import com.shadow.core.util.toast.ToastUtils;
import com.shadow.ui.recycler.ObjConverter;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author zhangyu
 * @date 2018/7/23
 */

public class ToTurnAddTaskDelegate extends RxShadowDelegate {
    public static ToTurnAddTaskDelegate create() {
        return new ToTurnAddTaskDelegate();
    }

    @BindView(R2.id.toolbar)
    Toolbar mToolbar;
    @BindView(R2.id.sp_supplier_name)
    Spinner mSpSupplierName;
    @BindView(R2.id.sp_part_code)
    Spinner mSpPartCode;
    @BindView(R2.id.et_count)
    EditText mEtCount;
    @BindView(R2.id.spinner_type)
    Spinner mSpType;
    private int mCurrentTypeId = 2;
    private String mPartCode;

    @Override
    public Object setLayout() {
        return R.layout.delegate_to_turn_add_task;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mToolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
            mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    pop();
                }
            });
            mToolbar.setTitle("新增翻包任务");
        }
        initSpType();
    }

    private void initSpType() {
        List<String> items = new ArrayList<>();
        items.add("大翻成盒");
        items.add("大翻成料架");
        items.add("大翻小再翻大");
        ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(), R.layout.row_spn, items);
        adapter.setDropDownViewResource(R.layout.row_spn_dropdown);
        mSpType.setAdapter(adapter);

        mSpType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if(position == 0){
                    mCurrentTypeId =2;
                }else if(position == 1){
                    mCurrentTypeId = 3;
                }else{
                    mCurrentTypeId = 1;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        getSupplierList();
        //getPartListBySupplier(25);
    }

    @OnClick(R2.id.tv_commit)
    public void onCommit() {
        //零件代码
        String code = mPartCode;
        if (code == null || code.isEmpty()) {
            ToastUtils.showToast(getContext(), "请选择零件代码!");
            return;
        }

        String count = mEtCount.getText().toString();
        if (code.isEmpty() || count.isEmpty()) {
            ToastUtils.showToast(getContext(), "请填写翻包数量!");
            return;
        }
        mDisposables.add(RxRestClient.builder()
                .loader(getContext())
                .url("WMS/backstage/turnbag/addTurnBagTask")
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        int code = new ResultConverter().getCode(response);
                        if (code == 1) {
                            ToastUtils.showToast(getContext(), "提交成功!");
                            //TODO 提交成功后返回去修改状态
                            EventBus.getDefault().post(new RefreshAddTurnEvent());
                            pop();
                        } else if (code == -1) {
                            ToastUtils.showToast(getContext(), "零件库存不足!");
                        } else {
                            ToastUtils.showToast(getContext(), "系统错误!");
                        }
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        ToastUtils.showToast(getContext(), msg);
                    }
                })
                .params("partnum", code)
                .params("num", count)
                .params("type", mCurrentTypeId)
                .build()
                .unRestGet());
    }

    private void getPartListBySupplier(int supId) {
        mDisposables.add(RxRestClient.builder()
                .loader(getContext())
                .url("WMS/backstage/parts/getBySupid")
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        try {
                            JSONArray jsonArray = JSONObject.parseObject(response)
                                    .getJSONArray("list");
                            final int size = jsonArray.size();
                            final List<String> list = new ArrayList<>();
                            for (int i = 0; i < size; i++) {
                                final JSONObject object = jsonArray.getJSONObject(i);
                                String partCode = object.getString("partsNum");
                                if (partCode != null) {
                                    list.add(partCode);
                                }
                            }
                            if (mSpPartCode != null) {
                                if (!list.isEmpty()) {
                                    mPartCode = list.get(0);
                                } else {
                                    mPartCode = "";
                                }
                                ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(), R.layout.row_spn, list);
                                adapter.setDropDownViewResource(R.layout.row_spn_dropdown);
                                mSpPartCode.setAdapter(adapter);
                                mSpPartCode.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                    @Override
                                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                        mPartCode = list.get(position);
                                    }

                                    @Override
                                    public void onNothingSelected(AdapterView<?> parent) {

                                    }
                                });
                            }
                        } catch (Exception e) {
                            ToastUtils.showToast(getContext(), "零件代码获取错误!");
                        }
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {

                    }
                })
                .params("supid", supId)
                .build()
                .unRestGet());
    }

    private void getSupplierList() {
        mDisposables.add(RxRestClient.builder()
                .url("WMS/backstage/supplier/getlist")
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        try {
                            final JSONArray jsonArray = JSONObject.parseObject(response)
                                    .getJSONArray("rows");
                            final int size = jsonArray.size();
                            final List<SupplierEntry> list = new ArrayList<>();
                            for (int i = 0; i < size; i++) {
                                final JSONObject object = jsonArray.getJSONObject(i);
                                SupplierEntry supplierEntry = new ObjConverter<SupplierEntry>().
                                        convert(object.toJSONString(), new TypeReference<SupplierEntry>() {
                                        });
                                if (supplierEntry != null) {
                                    list.add(supplierEntry);
                                }
                            }
                            if (mSpSupplierName != null) {
                                final int[] supplierId = {0};
                                if (!list.isEmpty()) {
                                    supplierId[0] = list.get(0).getSupplierId();
                                    ArrayAdapter<SupplierEntry> adapter = new ArrayAdapter<>(getContext(), R.layout.row_spn, list);
                                    adapter.setDropDownViewResource(R.layout.row_spn_dropdown);
                                    mSpSupplierName.setAdapter(adapter);
                                    mSpSupplierName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                        @Override
                                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                            supplierId[0] = list.get(position).getSupplierId();
                                            getPartListBySupplier(supplierId[0]);
                                        }

                                        @Override
                                        public void onNothingSelected(AdapterView<?> parent) {

                                        }
                                    });
                                    getPartListBySupplier(supplierId[0]);
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {

                    }
                })
                .build()
                .unRestGet());
    }
}
